package com.aaa.web.session; /**
 * @ProjectName Java_web_demo_20230304
 * @Author 李江波
 * @Date 2023/03/04 上午 09:49
 * @Version 1.0.0
 * @Description
 */

import com.aaa.web.entity.Emp;
import com.aaa.web.service.emp.EmpServiceImpl;
import com.aaa.web.service.emp.Impl.EmpService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

@WebServlet(name = "SessionServlet", value = "/SessionServlet/*")
public class SessionServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码格式
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html");
        //获取url或者uri
        StringBuffer requestURL = req.getRequestURL();
        //url=localhost:8080/EmpServlet?toUpdate 通过url定位到资源 （河南省郑州市高新区科学大道与长春路交叉口向西200米郑大南门）
        System.out.println("请求的URL = " + requestURL);
        String requestURI = req.getRequestURI();
        //uri = EmpServlet/ToUpdate 只是资源的名称 无法定位到具体资源  （郑州大学）
        System.out.println("请求的URI = " + requestURI);
        //截取字符串。获取执行请求的最后部门字符串  requestMethodName = query add toUpdate update delete其中一个
        String requestMethodName = requestURI.substring(requestURI.lastIndexOf("/") + 1);
        //定义转发路径
        String toGoUri =null;
        //执行各种方法
        switch(requestMethodName){
            case"login":
                toGoUri = this.login(req, resp);
                break;
            case"user":
                toGoUri = this.user(req, resp);
                break;
            default:
                break;
        }
        //判断不空
        if (toGoUri!=null){
            //转发
            req.getRequestDispatcher(toGoUri).forward(req,resp);
        }
    }

    private String user(HttpServletRequest req, HttpServletResponse resp) {
        HttpSession session = req.getSession();
        String userName =(String)session.getAttribute("userName");
        System.out.println(userName);
        session.invalidate();
        System.out.println("session销毁");
        return "/login.jsp";
    }

    private String login(HttpServletRequest req, HttpServletResponse resp) {
        String userName = req.getParameter( "userName");
        String password = req.getParameter( "password");
        EmpService empService = new EmpServiceImpl();
        Emp emp = empService.queryName(userName, password);
        if (emp!=null){
            HttpSession session = req.getSession();
            session.setAttribute("userName",userName);
            System.out.println("开启session");
            return "/index.jsp";
        }else {
            req.setAttribute("error","账号或密码错误");
            return "/login.jsp";
        }
    }
}
